package com.tangqihang229350526.mynote

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.tangqihang229350526.mynote.database.Note
import com.tangqihang229350526.mynote.database.NoteDatabase
import com.tangqihang229350526.mynote.databinding.FragmentHomeBinding
import com.tangqihang229350526.mynote.repository.NoteRepository
import com.tangqihang229350526.mynote.viewmodel.HomeViewModel

class HomeFragment : Fragment() {
    private var binding: FragmentHomeBinding? = null
    private var database: NoteDatabase? = null
    private var homeViewModel: HomeViewModel? = null
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        homeViewModel = ViewModelProvider(this)[HomeViewModel::class.java]
        binding = FragmentHomeBinding.inflate(inflater, container, false)
        val root: View = binding!!.root
        val adapter: NoteAdapter = NoteAdapter()
        binding!!.lv.adapter = adapter
        binding!!.lv.setOnItemClickListener { parent, view, position, id ->
            val note = adapter.getData()[position]
            if (note.time != null) {
                val intent = Intent(context, NoteDetailActivity::class.java)
                intent.putExtra("id", note.id)
                startActivity(intent)
            }
        }
        homeViewModel!!.getData().observe(this) { v: List<Note>? ->
            adapter.setNewData(
                v
            )
        }
        database = NoteDatabase(context)
        binding!!.btnAdd.setOnClickListener {
            startActivity(
                Intent(
                    context,
                    AddNoteActivity::class.java
                )
            )
        }
        binding!!.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                val key = s.toString()
                homeViewModel!!.setData(NoteRepository.instance?.query(database, key) as List<Note>)
            }

            override fun afterTextChanged(s: Editable) {}
        })
        return root
    }

    override fun onResume() {
        super.onResume()
        val key = binding!!.etSearch.text.toString()
        homeViewModel?.setData(NoteRepository.instance?.query(database, key) as List<Note>)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
    }

    inner class NoteAdapter : BaseAdapter() {
        private val data: MutableList<Note> = ArrayList()
        fun setNewData(v: List<Note>?) {
            data.clear()
            if (v != null) {
                data.addAll(v)
            }
            notifyDataSetChanged()
        }

        fun getData(): List<Note> {
            return data
        }

        override fun getCount(): Int {
            return data.size
        }

        override fun getItem(position: Int): Any {
            return data[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
            var view = convertView
            val note = data[position]
            if (view == null) {
                view = if (note.layoutType === 0) {
                    LayoutInflater.from(parent.context).inflate(R.layout.layout_type, parent, false)
                } else {
                    LayoutInflater.from(parent.context).inflate(R.layout.layout_note, parent, false)
                }
            }
            val tvTitle = view?.findViewById<TextView>(R.id.tv_title)
            if (tvTitle != null) {
                tvTitle.text = note.title
            }
            if (note.layoutType === 1) {
                val tvContent = view?.findViewById<TextView>(R.id.tv_content)
                val tvTime = view?.findViewById<TextView>(R.id.tv_time)
                val iv = view?.findViewById<ImageView>(R.id.iv)
                if (tvContent != null) {
                    tvContent.text = note.content
                }
                if (tvTime != null) {
                    tvTime.text = note.time
                }
                if (iv != null) {
                    Glide.with(parent.context).load(note.image).into(iv)
                }
            }
            return view
        }
    }
}